var express = require("express");
var router = express.Router();
const { foodFind, cateFind, getNextSequenceValue } = require("./funcs");
const { deepCopyJson } = require("../utils");

const fs = require('fs')

const Food = require("../mongoose/models/foods");

/* GET home page. */
router.get("/list", async function (req, res, next) {
  console.log(req.query);
  foodFind((foods) => {
    res.status(200).send({
      code: 1,
      data: foods,
      msg: "操作成功",
    });
  }, req.query);
});

// 添加食品
router.post("/add", async function (req, res, next) {
  const body = req.body;
  console.log(body, "body");
  body.id = await getNextSequenceValue("food_id");

  new Food(body).save(function (err, food) {
    if (err) {
      return res.status(500).json({
        code: 500,
        message: err,
      });
    }

    res.status(200).json({
      code: 1,
      data: food,
      msg: "添加成功!",
    });
  });
});

// 删除食品
router.post("/del", function (req, res, next) {
  const { id } = req.body;
  // console.log(typeof id == Number);
  Food.deleteOne({ id: Number(id) }, (err, data) => {
    if (err) {
      res.send({
        code: 999,
        msg: err,
      });
      return;
    }

    console.log(data, "删除一个食物");

    res.send({
      code: 1,
      msg: "删除成功!",
      data,
    });
  });
});

router.post("/edit", function (req, res, next) {
  let id = Number(req.body.id);
  req.body.id = id;

  Food.findOneAndUpdate({ id }, { $set: req.body }, function (err, data) {
    if (err) {
      res.send({
        code: 999,
        msg: "数据库发生错误!",
      });
      return;
    } else if (!data) {
      res.send({
        code: 999,
        msg: "未查找到相关数据!",
      });
      return;
    } else if (data) {
      res.status(200).send({
        code: 1,
        msg: "修改成功!",
      });
    }
  });
});

router.get("/getlistwithcate", (req, res) => {
  console.log(req.query);
  cateFind((cates) => {
    foodFind((foods) => {
      let foodDeep = deepCopyJson(cates);
      foods.forEach((item) => {
        let ids = item.catid ? item.catid.split(",") : [];
        ids.forEach((item2) => {
          foodDeep.forEach((item3) => {
            if (Number(item2) === Number(item3.catid)) {
              if (!item3.list) {
                item3.list = [];
              }
              item3.list.push(item);
            }
          });
        });
      });
      cates = cates.map((item) => ({
        label: item.name,
        value: item.catid,
      }));

      res.send({
        code: 1,
        msg: "获取成功!",
        foods: foodDeep,
        cates,
      });
    }, req.query);
  }, { store: req.query.store });
});


/**
 * 给Food（Model） 添加一个字段 store: "1"
 */
router.get("/insertoneprop", async function (req, res, next) {
  if (req.query.key !== 'INSERTONEPROPREWCSQWEJGKR123DFG12') {
    res.send({
      code: 500,
      msg: '暂无权限'
    }) 
    return
  }
  Food.updateMany({}, { store: "1" }, function (err, docs) {
    if (err) {
      res.send({
        code: 500,
        msg: err
      })
    } else {
      res.send({
        code: 1,
        msg: '操作成功！'
      })
    }
  });
});


router.get("/getmockfood", async function (req, res, next) {
  const data = fs.readFileSync(__dirname + '/../utils/mockfoods.json', 'utf-8')
  const cates = fs.readFileSync(__dirname + '/../utils/mockcates.json', 'utf-8')
  // console.log(data, 'data');
  res.send({
    code: 1,
    msg: '请求成功',
    data: JSON.parse(data),
    cates: JSON.parse(cates)
  })
});

module.exports = router;
